//
//  HMSessionCell.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/8/27.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

protocol HMSessionCellDelegate: class {
    func sessionCellBtn(sender: UIButton, doctor: Bool)
}


/// 会话cell, 全部会话入口都用这个
class HMSessionCell: HMTableViewCell {
    let icon = UIImageView()
    let name = UILabel()
    let describe = UILabel()
    let statusLabel = UILabel()
    let btn = UIButton()
    //当前咨询人数
    var consultingNum: Int = 0
    //医生ID、用户
    var userId = ""
    // 生成的咨询id
    var consultId = ""
    //医生评分，0-10分
    var evaluate = 0
    var isTitleStr = "" // 判断是进入医生服务，进入诊室、邀请列表。
    var isDoctor = false //默认
    // 健康咨询状态: 1 邀请咨询，2 等待回应，3 等待付款, 4 立即沟通, 5咨询结束, 6 咨询关闭
    var status = 1
    weak var delegate : HMSessionCellDelegate?
    
    //
    var iconBlock: (( _ cell: HMSessionCell) -> ())?
    
    /// message数组数据回调
//    var messageList: [Any]?   //(([Any])-> ())?
    /// 个人信息回调
    var userProfile: TIMUserProfile?    //(()-> ())?
    
    override func setupViews(view: UIView) {
        view.addSubview(icon)
        view.addSubview(name)
        view.addSubview(describe)
        
        btn.addSubview(statusLabel)
        view.addSubview(btn)
        
        icon.leadingAlign(view: view, predicate: "8")
        icon.centerYAlign(view: view, predicate: "0")
        icon.heightConstrain(predicate: "75")
        icon.widthConstrain(predicate: "75")
        icon.layer.cornerRadius = 40
        icon.layer.masksToBounds = true
        icon.addTapGesture(target: self, action: #selector(addPatientBtn))
//        icon.backgroundColor = UIColor.yellow
        
        name.leadingHorizontally(view: icon, predicate: "10")
        name.centerYAlign(view: icon, predicate: "-20")
        name.trailingHorizontally(view: btn)
        name.heightConstrain(predicate: "40")
        name.font = configure.shareConfigure.HMSize_15
        
        
        describe.leadingHorizontally(view: icon, predicate: "10")
        describe.trailingHorizontally(view: btn)
        describe.centerYAlign(view: icon, predicate: "20")
        describe.heightConstrain(predicate: "40")
        describe.font = configure.shareConfigure.HMSize_15
        
        
        btn.trailingAlign(view: view)
        btn.centerYAlign(view: view)
        btn.heightConstrain(predicate: "60")
        btn.widthConstrain(predicate: "60")
        btn.setTitle("", for: UIControlState.normal)
        btn.setTitleColor(UIColor.black, for: UIControlState.normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        btn.layer.cornerRadius = 30
        btn.addTarget(self, action: #selector(sessionCellBtn), for: UIControlEvents.touchUpInside)
        
        
//        statusLabel.centerXYAlign(view: btn)
        statusLabel.textColor = UIColor.white
//        statusLabel.widthConstrain(predicate: "44")
//        statusLabel.heightConstrain(predicate: "44")
        statusLabel.lineBreakMode = NSLineBreakMode.byWordWrapping;
        statusLabel.text = " 邀请\n 咨询"
        statusLabel.numberOfLines = 0
        
    }
    
    
    /// json 数据入口
    override func setJson(json: JSON) {
        

        if isDoctor  { //医生
            // 咨询列表入口""
            if isTitleStr == "医生服务" {
                print("json", json)
                self.userId = json["doctorId"].stringValue
                let _imgUrl = configure.shareConfigure.IP_diagonal + (json["doctorIcon"].stringValue)
                icon.img(url: _imgUrl)
                name.text = json["doctorName"].stringValue
                describe.text = json["desc"].stringValue
            }else {
            self.userId = json["id"].stringValue
            self.evaluate = json["evaluate"].intValue
            let _imgUrl = configure.shareConfigure.IP_diagonal + (json["iconUrl"].stringValue)
            icon.img(url: _imgUrl)
            name.text = "\(json["nickname"].stringValue) (\(json["level"].stringValue))"
            describe.text = json["hospital"].stringValue
            
      
//            statusLabel.text = " 咨询 "
                
                
            btn.isEnabled = true
            statusLabel.textColor = UIColor.white
            statusLabel.text = " 进入\n 咨询 "
            btn.backgroundColor = configure.shareConfigure.HMColor1
            }
        }else { //不是医生
            
           self.userId = json["userId"].stringValue
           self.consultId = json["consultId"].stringValue
            
           let _imgUrl = configure.shareConfigure.IP_diagonal + (json["iconUrl"].stringValue)
           icon.img(url: _imgUrl)
           name.text = "\(json["nickname"].stringValue)  \(json["age"].stringValue)  \(json["sex"].stringValue)"
           describe.text = json["illnessDesc"].stringValue
            
            
//            self.status = json["status"].intValue
//            if self.status == 1 {
//                 statusLabel.text = " 邀请\n 咨询"
//                 btn.isEnabled = true
//                 statusLabel.textColor = UIColor.white
//                btn.backgroundColor = configure.shareConfigure.HMColor1
//            }else if self.status == 2 {
//
//                statusLabel.text = " 等待\n 回应"
//                btn.isEnabled = false
//                btn.backgroundColor = UIColor.gray
//            }else if self.status == 3 {
//                // 医生没有这个状态
//                statusLabel.text = " 等待\n 付款"
//                btn.backgroundColor = UIColor.gray
//            }else if self.status == 4 {
//                statusLabel.text = " 正在\n 沟通"
//                 btn.isEnabled = false
//                btn.backgroundColor = configure.shareConfigure.HMColor3
//            }else if self.status == 5 || self.status == 6 {
//                //咨询结束 //咨询关闭
//            }else { //异常状态
//
//            }

        }
        
        self.status = json["status"].intValue
        if self.status == 1 {
            statusLabel.text = " 邀请\n 咨询"
            btn.isEnabled = true
            statusLabel.textColor = UIColor.white
            statusLabel.centerXYAlign(view: btn)
            statusLabel.widthConstrain(predicate: "44")
            statusLabel.heightConstrain(predicate: "44")
            btn.backgroundColor = configure.shareConfigure.HMColor1
        }else if self.status == 2 {
            
            statusLabel.text = " 等待\n 回应"
            statusLabel.centerXYAlign(view: btn)
            statusLabel.widthConstrain(predicate: "44")
            statusLabel.heightConstrain(predicate: "44")
            btn.isEnabled = false
            btn.backgroundColor = UIColor.gray
        }else if self.status == 3 {
            // 医生没有这个状态
            statusLabel.text = " 等待\n 付款"
            statusLabel.centerXYAlign(view: btn)
            statusLabel.widthConstrain(predicate: "44")
            statusLabel.heightConstrain(predicate: "44")
            btn.backgroundColor = UIColor.gray
        }else if self.status == 4 {
            statusLabel.text = "正在沟通"
            statusLabel.font = UIFont.systemFont(ofSize: 12)
            statusLabel.backgroundColor = configure.shareConfigure.HMColor1
           
            statusLabel.centerYAlign(view: self, predicate: "-20")
//            statusLabel.centerXAlign(view: self, predicate: "0")
            
            statusLabel.trailingAlign(view: self, predicate: "-20")
            statusLabel.heightConstrain(predicate: "20")
            statusLabel.widthConstrain(predicate: "60")
            statusLabel.layer.cornerRadius = 100
            statusLabel.textAlignment = .center
            btn.isEnabled = false
//            btn.backgroundColor = configure.shareConfigure.HMColor1
        }else if self.status == 5 || self.status == 6 {
            //咨询结束 //咨询关闭
            
        }else { //异常状态
//            statusLabel.trailingAlign(view: self)
            statusLabel.centerXYAlign(view: btn)
            statusLabel.widthConstrain(predicate: "44")
            statusLabel.heightConstrain(predicate: "44")
        }
        
        
    }
    
    /// 腾讯数据模型入口
    func setIMData(data: TIMConversation!) {
        // 对方id
        let otherId: String = data.getReceiver()!
        var timeData = ""
        
        
        let msgList = data.getLastMsgs(1)
        HMElem.analysisMessage(list: msgList!, sort: false, doctorProfile: nil) { (elem, userInfo, isO, classType) in
            if  classType == TIMTextElem.self {
                let text_elem = elem as! TIMTextElem
                self.describe.text = text_elem.text
            }else {
                self.describe.text = ""
            }
            //timestamp
            //                       timeData = Date.updateTimeToCurrennTime(timeStamp: ms.timestamp().timeIntervalSince1970) // 时间戳
        }

        
        var ary = Array<String>()
        ary.append(otherId)
        TIMFriendshipManager.sharedInstance()?.getUsersProfile(ary, succ: { (arr) in
            let profile = arr![0] as! TIMUserProfile
        
            self.userProfile = profile
            let _imgUrl = configure.shareConfigure.IP_diagonal + profile.faceURL
            self.icon.img(url: _imgUrl)
            
//            var sex = "--"
//            if profile.gender == .GENDER_MALE  {
//                sex = "男"
//            }else if profile.gender  == .GENDER_FEMALE {
//                sex = "女"
//            }else {
//                sex = "--"
//            }
            //profile.birthday
            
            self.name.text = profile.nickname  + timeData
            
        }, fail: { (code, err) in
            print("获取信息失败-->\(code)")
        })
        
        // 隐藏按钮
        self.btn.isHidden = true
        
    }
    
//    func setIMData(data: TIMConversation!) -> (msgAry:[Any], doctorInfo:TIMUserProfile) {
//
//        return ([], TIMUserProfile())
//    }
    
    /// cell 内的状态按钮
    @objc func sessionCellBtn(sender: UIButton) {
 //
        
       
            if isDoctor {
                var dic = Dictionary<String, Any>()
                dic["doctorId"] = self.userId
                dic["consultId"] = self.consultId
                sender.dictionary = dic
                delegate?.sessionCellBtn(sender: sender, doctor: isDoctor)
            }else {
                if HMLoginParam.share.getCurrentId == self.userId {
                    RKDropdownAlert.title("温馨提醒!", message: "不能邀请自己！")
                }else {
                
                if status == 1 {
                 statusLabel.text = " 等待\n 回应"
                 sender.backgroundColor = UIColor.gray
                }
                var dic = Dictionary<String, Any>()
                dic["doctorId"] = self.userId
                dic["consultId"] = self.consultId
                sender.dictionary = dic
                delegate?.sessionCellBtn(sender: sender, doctor: isDoctor)
                }
           }

    }
    @objc func addPatientBtn(sender: UITapGestureRecognizer) {
        self.iconBlock?(self)
    }
    
    
    
    
}
